'''
生成器
1. 把列表生成式的[]变成（） 就变成了生成器

2. 用yield 关键字
    线程在执行到yield时， 可以中断， 转而执行其他程序， 在需要的时候再回来继续执行
迭代器
可迭代对象

'''
from queue import Queue
#  1. ()
x = (_*_ for _ in range(20))
for i in x:
    print(i)
 # 可以用next(x) 调用 ， 最后抛出StopIteration

#  2. yield
def febolaqi(x):
     a, b, c = 0, 0 ,1
     while a < x:
         yield c
         b, c = c, b+c
         a+=1


for i in febolaqi(10):
    print(i)

# 生成器是迭代器


def hello():
    print('hh');
    x = yield 'dd'
    print('xx: ', x)

s = hello()
next(s)
# s.send('1000')

def fib(n):   # 斐波拉契数列
    a, b  = 0, 1
    while n > 0:
        c = a + b
        yield b
        a = b
        b = c
        n -= 1

for i in fib(10):
    print(i)


from collections import  namedtuple
Resclass = namedtuple('Res', 'count arvage')
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        term = yield
        if term is None:
            break
        total += term
        count += 1
        average = total /count

    return Resclass(count, average)

def grouper(storages, key):
    while True:
        storages['key'] = yield from averager()

def client():
    process_data = {
        'boys_2': [23.4,23.3,23.5,56.8,56.8],
        'boys_1': [1.4,23.4,5.4,5.2,1.4]
    }
    storages = {}
    for k, v in process_data.items():
        coroutine = grouper(storages, k)
        next(coroutine)
        for dt in v:
            coroutine.send(dt)
        coroutine.send(None)
    print(storages)
client()

def averager():
    total = 0.0
    count = 0
    avg = None

    while True:
        num = yield avg
        total += num
        count += 1
        avg = total/count

# run
ag = averager()
# 预激协程
print(next(ag))     # None

print(ag.send(10))  # 10
print(ag.send(20))  # 15

















